package net.zwj.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EchoAioServer {

	private final int port;

	public static void main(String[] args) {
		int port = 8000;
		new EchoAioServer(port);

	}

	public EchoAioServer(int port) {
		this.port = port;
		listen();
	}

	private void listen() {
		try {
			ExecutorService executorService = Executors.newCachedThreadPool();
			AsynchronousChannelGroup threadGroup = AsynchronousChannelGroup
					.withCachedThreadPool(executorService, 1);
			
			try(AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(threadGroup)){
				server.bind(new InetSocketAddress(port));
				System.out.println("echo listend on "+port);
				server.accept(null, new AcceptCompletionHandler(server));
				
				try {  
                    // Wait for ever  
                    Thread.sleep(Integer.MAX_VALUE);  
                } catch (InterruptedException ex) {  
                    System.out.println(ex);  
                }  
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
